package com.benshou.bsoa.service.yida;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.aliyun.dingtalkyida_2_0.models.GetFormDataByIDResponse;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataSecondGenerationResponse;
import com.benshou.bsoa.constants.SearchConstants;
import com.benshou.bsoa.dto.yida.req.YiDaReq;
import com.benshou.bsoa.dto.yida.req.YiDaSearchReq;
import io.micrometer.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.benshou.bsoa.constants.ProgressConstants.*;
import static com.benshou.bsoa.constants.TaskConstants.*;


/*
 * 处理项目文档汇总的服务类
 * 该服务类负责从任务表单获取formInstanceId，并将数据更新到文档汇总表单
 */


@Service
public class TaskDocumentSummaryService {

    private static final Logger log = LoggerFactory.getLogger(TaskDocumentSummaryService.class);

    @Autowired
    private GetYiDaService getYiDaService;

    @Autowired
    private UpdateYiDaService updateYiDaService;

    @Autowired
    private SearchYiDaService searchYiDaService;

    @Value("${dingding.benshou.userId}")
    private String userId;

    @Value("${dingding.benshou.task.formUuid}")
    private String taskFormUuid;

    @Value("${dingding.benshou.document.formUuid}")
    private String documentSummaryFormUuid;



    /**
     * 获取任务表单的formInstanceId
     * @param formInstanceId 请求参数
     * @return formInstanceId
     */
    public boolean updateTaskDocumentSummary(String formInstanceId) throws Exception {
        // 1. 获取任务表单数据
        YiDaReq yiDaReq = new YiDaReq(userId, taskFormUuid);
        yiDaReq.setFormInstanceId(formInstanceId);
        GetFormDataByIDResponse getFormDataByIDResponse = getYiDaService.querySingleFormData(yiDaReq);
        //项目关联表单
        String rawStrProject  = String.valueOf((getFormDataByIDResponse.getBody().formData.get(PROJECT_FORM_UUID)));
        //商机关联表单
        String rawStrBusiness = String.valueOf((getFormDataByIDResponse.getBody().formData.get(BUSINESS_FORM_UUID)));
        /** 在任务表单中存在项目和商机两种类型 选了一种另外中就会为null 所以需要提取关联表单中的title**/
        String actuallyTitle = null;
        if (rawStrProject != null && !rawStrProject.isEmpty()) {
            actuallyTitle = extractTitles(rawStrProject);
        } else if (rawStrBusiness != null && !rawStrBusiness.isEmpty()) {
            actuallyTitle = extractTitles(rawStrBusiness);
        }

        if (StringUtils.isBlank(actuallyTitle)) {
            throw new Exception("未能获取有效的项目或商机标题");
        }
        //存储附件的数据结构
        List<Map<String,?>> fileUrlList = new ArrayList<Map<String,?>>();

        // 3. 收集任务文档的附件
        processAttachmentRow(getFormDataByIDResponse.getBody().formData, fileUrlList, TASK_ATTACHMENT_UUID);
        // 4. 结果的处理
        return collectProjectAttachmentsToUpdate(actuallyTitle, fileUrlList);
    }

    /*
     * 根据项目名称收集所有项目文档的附件并且更新
     * @param projectName 项目名称
     */
    private boolean collectProjectAttachmentsToUpdate(String projectName,List<Map<String,?>> fileUrlList) throws Exception {
        // 构建搜索条件
        Map<String, Object> condition = new HashMap<>();
        condition.put(SearchConstants.KEY, PROJECT_NAME_DOCUMENT);
        condition.put(SearchConstants.VALUE, projectName);
        condition.put(SearchConstants.TYPE, SearchConstants.TEXT_TYPE);
        condition.put(SearchConstants.OPERATOR, SearchConstants.LIKE_OPERATOR);
        condition.put(SearchConstants.COMPONENT_NAME, SearchConstants.TEXT_FIELD_COMPONENT);
        // 将条件封装为列表
        List<Map<String, Object>> list = Arrays.asList(condition);
        // 搜索文档汇总表单
        YiDaSearchReq searchReq = new YiDaSearchReq(userId, documentSummaryFormUuid);
        searchReq.setSearchCondition(JSON.toJSONString(list));
        SearchFormDataSecondGenerationResponse response = searchYiDaService.searchFormData(searchReq);

        // 检查响应有效性
        if (response == null || response.getBody() == null || response.getBody().getData() == null || response.getBody().getData().isEmpty()) {
            throw new Exception("未找到匹配的文档汇总信息");
        }
        // 准备更新数据
        String summaryFormInstanceId = response.getBody().getData().get(0).getFormInstanceId();
        //项目文档记录的搜索数据
        Map<String, ?> formData = response.getBody().getData().get(0).getFormData();
        processAttachmentRow(formData, fileUrlList, DOCUMENT_SUMMARY_FORM_UUID);

        Map<String, Object> updateData = new HashMap<>();
        updateData.put(DOCUMENT_SUMMARY_FORM_UUID, fileUrlList);

        YiDaReq yiDaReq = new YiDaReq(userId, documentSummaryFormUuid);
        yiDaReq.setFormInstanceId(summaryFormInstanceId);
        yiDaReq.setFormDataJson(JSON.toJSONString(updateData));
        return updateYiDaService.updateFormData(yiDaReq).statusCode == HttpStatus.OK.value();
    }

    /**
     * 处理每一行的附件数据
     * @param row 当前行数据
     * @param fileArrayList 附件列表
     */
    private void processAttachmentRow(Map<String, ?> row, List<Map<String, ?>> fileArrayList,String ATTACHMENT_NAME) {
        Object attachmentField = row.get(ATTACHMENT_NAME);
        if (!(attachmentField instanceof String) || StringUtils.isBlank((String) attachmentField)) {
            return;
        }
        try {
            List<Map<String, Object>> attachmentList = JSON.parseObject(
                    (String) attachmentField,
                    new TypeReference<List<Map<String, Object>>>() {});
            if (attachmentList != null) {
                for (Map<String, ?> attachment : attachmentList) {
                    Map<String, Object> fileMap = new HashMap<>();
                    fileMap.put(DOWNLOAD_URL, String.valueOf(attachment.get("downloadUrl")));
                    fileMap.put(NAME, String.valueOf(attachment.get("name")));
                    fileArrayList.add(fileMap);
                }
            }
        } catch (Exception e) {
            // 记录日志但继续处理其他附件
            log.error("解析附件数据失败", e);
        }
    }


    /**
     * 从嵌套字符串 JSON 中提取 title 字段
     * @param rawStr 原始字符串，格式为带引号的 JSON 数组字符串
     */
    public String extractTitles(String rawStr) {
        if (rawStr == null || rawStr.isEmpty()) {
            log.warn("输入字符串为空或null，无法解析标题");
            return null;
        }
        try {
            String title = null;
            // 反序列化外层字符串为真正的 JSON 字符串
            String jsonStr = JSON.parseObject(rawStr, String.class);
            // 解析为 JSON 对象列表
            List<JSONObject> list = JSON.parseArray(jsonStr, JSONObject.class);
            // 遍历取出title 字段
            for (JSONObject obj : list) {
                title = obj.getString("title");
                log.info("Title: {}", title);
            }
            return title;
        } catch (Exception e) {
            log.error("解析 JSON 失败，输入字符串为：{}", rawStr, e);
        }
            return null;
    }
}
